package me.toalec.RankUp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import me.toalec.RankUp.util.Utility;

import org.bukkit.util.config.Configuration;

public class ConfigManager {
	
	ConfigManager(RankUp instance){
		this.instance = instance;
		config = this.instance.getConfiguration();
		configPath = "plugins/" + instance.getDataFolder().getName() + File.separator + "config.yml";
	}
	
	String getString(String path){
		config.load();
		return config.getString(path);
	}
	
	Boolean getBoolean(String path){
		config.load();
		return config.getBoolean(path, false);
	}
	
	boolean setValue(String path, Object value){
		boolean successful = false;
		try {
			ArrayList<String> configText = new ArrayList<String>();
			BufferedReader in = new BufferedReader(new FileReader(configPath));
			String line;
			while((line = in.readLine()) != null){
				configText.add(line);
			}
			in.close();
			
			int lineNumber = getNodeLineNumber(configText, path.split("\\."));
			if(lineNumber != -1){
				String str = configText.get(lineNumber);
				configText.set(lineNumber, str.substring(0, str.indexOf(":") + 1).concat(" " + value));
				successful = true;
			}else{
				return successful;
			}
			
			BufferedWriter out = new BufferedWriter(new FileWriter(configPath));
			for(String ln: configText){
				out.write(ln);
				out.newLine();
			}
			out.close();
			
		} catch (FileNotFoundException e) {
			Utility.printConsole("Config.yml not found.");
		} catch (IOException e) {
			Utility.printConsole("Error modifying config.yml.");
		}
		return successful;
	}
	
	HashMap<String, String> getAllWord_PackageHashMap(){
		
		HashMap<String, String> groupWord = new HashMap<String, String>();
		
		try {
			BufferedReader in = new BufferedReader(new FileReader(configPath));
			String line;
			while((line = in.readLine()) != null){
				if(!line.contains(whiteSpace)){
					line = line.substring(0, line.lastIndexOf(":"));
					groupWord.put(getString(line + ".rankup_word"), line);
				}
			}
			in.close();
		} catch (IOException e) {
			Utility.printConsole("Error retrieving information from config.yml.");
		}
		
		return groupWord;
	}
	
	ArrayList<String> getAllPackageNames(){
		ArrayList<String> packages = new ArrayList<String>();
		
		try {
			BufferedReader in = new BufferedReader(new FileReader(configPath));
			String line;
			while((line = in.readLine()) != null){
				if(!line.contains(whiteSpace)){
					packages.add(line.substring(0, line.lastIndexOf(":")));
				}
			}
			
			in.close();
		} catch (IOException e) {
			Utility.printConsole("Error getting package names from config.yml.");
		}
		
		return packages;
	}
	
	void addPackage(String packageName){
		ArrayList<String> packages = new ArrayList<String>();
		
		try {
		BufferedReader in = new BufferedReader(new FileReader(configPath));
		String line;
		while((line = in.readLine()) != null){
			packages.add(line);
		}
		
		in.close();
		
		packages.add(packageName + ":");
		
		for(String ln : defaultEntry){
			packages.add(ln);
		}
		
		BufferedWriter out = new BufferedWriter(new FileWriter(configPath));
		
		for(int i = 0; i < packages.size(); i++){
			out.write(packages.get(i));
			out.newLine();
		}
		
			out.close();
		} catch (IOException e) {
			Utility.printConsole("Error adding package to config.yml.");
		}
	}
	
	void removePackage(String packageName){
		ArrayList<String> packages = new ArrayList<String>();
		
		try {
			BufferedReader in = new BufferedReader(new FileReader(configPath));
			String line;
			while((line = in.readLine()) != null){
				if(!line.equals(packageName + ":"))
					packages.add(line);
				else{
					while((line = in.readLine()) != null && (line.contains(whiteSpace))){
						//do nothing
					}
				}
			}
			
			in.close();
			
			BufferedWriter out = new BufferedWriter(new FileWriter(configPath));
			
			for(int i = 0; i < packages.size(); i++){
				out.write(packages.get(i));
				out.newLine();
			}
		
			out.close();
		} catch (IOException e) {
			Utility.printConsole("Error removing package from config.yml.");
		}
	}
	
	void save(){
		config.save();
	}
	
	void load(){
		File file = new File(configPath);
		instance.getDataFolder().mkdir();
		
		if(!file.exists()){
			try {
				file.createNewFile();
				addDefaultValues();
				Utility.printConsole("Please fill in the config.yml file located in plugins/" + instance.getDescription().getName() + " to continue," + 
						" or use the console commands which can be listed by typing ru.");			
			} catch (IOException e) {
				Utility.printConsole("Error creating config.yml, disabling plugin.");
				instance.disablePlugin();
			}
		}
	}
	
	private void addDefaultValues(){
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(configPath));
			
			out.write("default:");
			out.newLine();
			for(String ln : defaultEntry){
				out.write(ln);
				out.newLine();
			}
			
			out.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private int getNodeLineNumber(ArrayList<String> configText, String[] nodes){
		for(int i = 0, j = 0; i < configText.size() && j < nodes.length; i++){
			if(configText.get(i).contains(getWhiteSpace(j) + nodes[j] + ":") && !configText.get(i).startsWith("#")){
				j++;
				if(j == nodes.length){
					return i;
				}
			}
		}
		return -1;
	}
	
	private String getWhiteSpace(int index){
		String str = "";
		if(index > 0){
			for(int i = 0; i < index; i++){
				str = str.concat(whiteSpace);
			}
		}
		return str;
	}
	
	private RankUp instance;
	private Configuration config;
	private String configPath;
	private String defaultEntry[] = {
			"    startingGroup: ''",
			"    endingGroup: ''",
			"    rankup_command_enabled: false",
			"    rankup_word_enabled: false",
			"    rankup_word: ''",
			"    rankup_sign_enabled: false"};
	private String whiteSpace = "    ";
}
